<template>
    <van-nav-bar title="确认订单" left-text="" left-arrow @click-left="goBack" />
    <!-- 收货地址 -->
    <van-contact-card type="add" @click="toAddressPage" v-if="JSON.stringify(address) == '{}'" />
    <van-contact-card type="edit" :tel="address.mobile" :name="address.consignee" @click="toAddressPage" v-else />

    <!-- 商品信息 -->
    <van-card v-for="item in cartlist" :key="item.id" :price="item.total" :desc="'库存：' + item.product.stock"
        :title="item.product.name" :thumb="item.product.thumb_text" @click-thumb="toPageProduct(item.proid)"
        :num="item.nums">
        <template #tags>
            <div>单价： {{ item.price }}</div>
        </template>
    </van-card>
    <!-- 订单备注 -->
    <van-cell-group inset>
        <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="50" placeholder="请输入订单备注"
            show-word-limit />
    </van-cell-group>
    <!-- 订单金额 -->
    <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit" />
</template>
<script setup>
const goBack = () => {
    history.back();
};
const router = useRouter();
const route = useRoute();
const { cookies } = useCookies();
const LoginUser = reactive(cookies.get("LoginUser") ?? {});
const address = ref(cookies.get("Address") ?? {})
const cartids = ref(route.query.cartids ?? 0)
const cartlist = ref([])
const remark = ref('')
const toAddressPage = () => {
    router.push('/business/address/index?action=order')
}
onBeforeMount(() => {
    getCartData();
    if (JSON.stringify(address.value) == '{}') {
        getAddressData()
    }
});
const getAddressData = async () => {
    let result = await Api.addressOder({
        busid: LoginUser.id
    });
    if (result.code == 1) {
        address.value = result.data
    }
}
const getCartData = async () => {
    let result = await Api.cartIndex({
        busid: LoginUser.id,
        cartids: cartids.value
    });
    if (result.code == 1) {
        cartlist.value = result.data
    }
}
const total = computed(() => {
    let num = 0;
    num = cartlist.value.reduce((acc, item) => acc + parseFloat(item.total), 0)
    return num * 100;
})

// 提交订单
const onSubmit = async () => {
    //传参 订单信息
    let data = {
        addressid: address.value.id,
        cartids: cartids.value,
        amount: (total.value / 100).toFixed(2),//金额 toFixed(2) 保留两位小数
        remark: remark.value,
        busid: LoginUser.id,
    }
    let result = await Api.orderAdd(data)//调取接口
    if (result.code == 1) {
        showSuccessToast({
            message: result.msg,
            onClose: function () {
                router.push("/business/order/index");
            },
        });
    } else {
        showFailToast(result.msg);
    }
}
</script>